package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.enums.UserStatusEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.media.dtos.WmUserDto;
import com.heima.model.media.dtos.WmUserLoginDto;
import com.heima.wemedia.dto.LoginResultDto;
import com.heima.wemedia.entity.WmUser;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    private static final Integer EXPIRE_MINUTE = 120;

    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * 保存自媒体用户信息
     * @param dto
     * @return
     */
    @Override
    public Integer saveWmUser(WmUserDto dto) {
        // 根据apUserId查询是否存在对应的自媒体账号
        // 如果有，则更新，没有，则insert
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getApUserId, dto.getApUserId());
        WmUser userDB = this.getOne(queryWrapper);
        if(userDB == null){
            // insert
            WmUser userInsert = buildUserInsert(dto);
            this.save(userInsert);
            return userInsert.getId();
        }else{
            // update
            WmUser userUpdate = buildUserUpdate(userDB.getId(), dto);
            this.updateById(userUpdate);
            return userUpdate.getId();
        }
    }

    @Override
    public Object login(WmUserLoginDto wmUserLoginDto) {
        //根据用户名查询用户信息
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName, wmUserLoginDto.getName());
        WmUser wmUser = this.getOne(queryWrapper);
        if (wmUser == null) {
            throw new LeadException(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }
        //密码匹配
        String passwordDB = wmUser.getPassword();
        String passwordIn = wmUserLoginDto.getPassword();
        boolean matches = encoder.matches(passwordIn, passwordDB);
        if (!matches) {
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //判断用户状态
        Integer status = wmUser.getStatus();
//        if (!Objects.equals(status, 9)) {
        if (UserStatusEnum.isValid(status)) {
            throw new LeadException(AppHttpCodeEnum.USER_STATUS_ERROR);
        }
        //生成user，token返回
        LoginResultDto resultDto = new LoginResultDto();
        resultDto.setUser(BeanHelper.copyProperties(wmUser, WmUser.class));
        resultDto.setToken(JwtUtils.generateTokenExpireInMinutes(wmUser.getId(), EXPIRE_MINUTE));
        return resultDto;

    }

    private WmUser buildUserInsert(WmUserDto dto) {
        WmUser user = BeanHelper.copyProperties(dto, WmUser.class);
        user.setType(0); //TODO
        user.setCreatedTime(new Date());
        return user;
    }

    private WmUser buildUserUpdate(Integer id, WmUserDto dto) {
        WmUser user = BeanHelper.copyProperties(dto, WmUser.class);
        user.setId(id);
        user.setApUserId(null);
        return user;
    }

}
